/**
 * Created by chu on 2017/10/10 0010.
 * bw 优化 2020/07/29
 */
 const EventListener = {
    regsiter: {},
    on: function (name, method, target) {
      if (!this.regsiter.hasOwnProperty(name)) {
        this.regsiter[name] = [];
      } else {
        let idx = this.regsiter[name].findIndex(ele => ele.target == target)
        // 同名 同this 直接删除
        if (idx != -1) {
          this.regsiter[name].splice(idx, 1)
        }
      }
      this.regsiter[name].push({ callback: method, target: target });
    },
  
    emit: function (name) {
      if (this.regsiter.hasOwnProperty(name)) {
        let handlerList = this.regsiter[name];
        let handler = handlerList[0];
        let args = [];
        for (let j = 1; j < arguments.length; j++) {
          args.push(arguments[j]);
        }
        return handler.callback.apply(this, args);
      }
    },
    off: function (name, target) {
      if (this.regsiter.hasOwnProperty(name)) {
        let idx = this.regsiter[name].findIndex(ele => ele.target == target)
        // 抛出异常事件
        if (idx === -1) {
          return new Error('无该绑定事件')
        }
        // 移除事件
  
        this.regsiter[name].splice(idx, 1)
        if (this.regsiter[name].length === 0) {
          delete this.regsiter[name]
        }
      }
    },
    fire: function (name) {
      if (this.regsiter.hasOwnProperty(name)) {
        let handlerList = this.regsiter[name];
        let handler = handlerList[0];
        let args = [];
        for (let j = 1; j < arguments.length; j++) {
          args.push(arguments[j]);
        }
        return handler.callback.apply(this, args);
      }
    },
  }
  export default EventListener;